package mobilecontrollers

import (
	"github.com/astaxie/beego"
	"time"
	"alarmservice/www/apistore"
	"alarmservice/com"
	"alarmservice/model"
)

type LoginController struct {
	baseController
}

func (c *LoginController) NextPrepare() {
	c.NeedParams = true
}

func (c *LoginController) Post() {
	if !c.HaveParams {
		c.returnJson(com.ApiUnknowFailed(com.ApiErrMsgNoJson))
		return

	}

	userName, userNameOk := c.ParamsJson.CheckGet("username")
	passWord, passWordOk := c.ParamsJson.CheckGet("password")

	if !userNameOk || !passWordOk {
		c.returnJson(com.ApiUnknowFailed(com.ApiErrMsgNeedParam))
		return
	}

	adminUser, err := model.GetAdminUserByUserNamePass(userName.MustString(), passWord.MustString())
	if err != nil {
		c.returnJson(com.ApiUnknowFailed("username or password error"))
		return
	}
	
	//获取设备信息
	deviceInfo, deviceInfoOk := c.ParamsJson.CheckGet("device_data")
	if !deviceInfoOk {
		c.returnJson(com.ApiUnknowFailed("need device info!"))
		return
	}
	
	os, err := deviceInfo.Get("os").String()
	version, err := deviceInfo.Get("version").String()
	if err != nil {
		c.returnJson(com.ApiUnknowFailed("device info error!"))
		return
	}
	
	//检查是否已经存在了
	mobileLogin, err := model.GetMobileLoginByUid(adminUser.Id)
	if err != nil && err != model.ErrNotExist {
		beego.Warning(err)
		c.returnJson(com.ApiUnknowFailed(com.ApiErrMsgSystem))
		return
	}
	
	if err != nil {
		//插入数据
		mobileLogin = new(model.MobileLogin)
		mobileLogin.Uid = adminUser.Id
		mobileLogin.Os = os
		mobileLogin.Version = version
		mobileLogin.LastLoginTime = time.Now()
		mobileLogin.CreateTime = mobileLogin.LastLoginTime
		
		err := model.Insert(mobileLogin)
		if err != nil {
			beego.Warning(err)
			c.returnJson(com.ApiUnknowFailed(com.ApiErrMsgSystem))
			return
		}
		
	} else {
		//修改登录数据
		mobileLogin.Os = os
		mobileLogin.Version = version
		mobileLogin.LastLoginTime = time.Now()
		err := model.UpdateById(adminUser.Id, mobileLogin)
		if err != nil {
			beego.Warning(err)
			c.returnJson(com.ApiUnknowFailed(com.ApiErrMsgSystem))
			return
		}
	}

	token := apistore.NewToken(adminUser.Id)

	c.returnJson(com.ApiSucc(token))
	return
}
